<template>
    <div class="white-box">
        <div class="table-mb">
            <!-- <el-button type="default" plain @click="allDel">批量删除</el-button> -->
            <el-button type="primary" @click="clickAdd">添加公共商品</el-button>
        </div>
        <div class="task-one">
            <div class="task-one__item">
                <span class="task-one__label">商品名称：</span>
                <el-input placeholder="输入商品名称搜索" v-model.trim="good_name" size="default" clearable></el-input>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">商品分类：</span>
                <el-select v-model="class_id" clearable placeholder="输入可筛选分类" filterable :filter-method="filterClass" @clear="clearCate">
                    <el-option :label="item.title" :value="item.cate_id" v-for="item in cate_arrs" :key="item.title" />
                </el-select>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">商品等级：</span>
                <el-select v-model="level_id" clearable placeholder="请选择商品等级">
                    <el-option :label="item.level_name" :value="item.level_id" v-for="item in pub_options.leave_list" :key="item.level_id" />
                </el-select>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">商品颜色：</span>
                <el-select v-model="colors_id" clearable placeholder="请选择颜色分类">
                    <el-option :label="item.title" :value="item.color_id" v-for="item in pub_options.color_list" :key="item.color_id" />
                </el-select>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">添加时间：</span>
                <el-date-picker
                    v-model="area_time"
                    type="daterange"
                    unlink-panels
                    value-format="YYYY-MM-DD"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                />
            </div>
            <div class="task-one__btn task-wrap-btn clearfix">
                <el-button type="primary" :loading="search_btn" :icon="Search" @click="handleSearch">搜索</el-button>
                <el-button type="default" @click="clickImportOrder">导出</el-button>
            </div>
        </div>

        <el-table
            class="table-mb"
            v-loading="loading"
            :data="arr_data"
            :header-cell-style="{ background: '#F5F7FA' }"
            element-loading-background="rgba(255, 255, 255, 0.6)"
        >
            <el-table-column label="商品名称" min-width="240">
                <template #default="{ row }">
                    <div class="table-lr">
                        <el-image class="table-lr__img" loading="lazy" :src="proxy.imgUrl + row.product_img + '!img_400'" fit="cover" v-if="row.product_img" />
                        <div class="table-lr__right line-two">
                            {{ row.product_name }}
                        </div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="cate_title" label="商品分类" min-width="120"></el-table-column>
            <el-table-column prop="color" label="颜色" min-width="100"></el-table-column>
            <el-table-column label="等级" min-width="140">
                <template #default="{ row }">
                    <p>{{ row.product_levels }}</p>
                </template>
            </el-table-column>
            <el-table-column label="规格" min-width="120">
                <template #default="{ row }">
                    <p>{{ row.norm }}/{{ row.unit }}</p>
                </template>
            </el-table-column>
            <el-table-column label="排序" width="120">
                <template #default="{ row }">
                    <el-input
                        v-model.trim="row.order_by"
                        clearable
                        placeholder="输入排序"
                        oninput="value=value.replace(/[^\d]/g,'')"
                        style="width: 90px"
                        @change="() => inputSort(row)"
                    />
                </template>
            </el-table-column>
            <el-table-column prop="sales" label="销量" min-width="100"></el-table-column>
            <el-table-column prop="created_at_label" label="添加时间" min-width="160"></el-table-column>
            <el-table-column label="操作" width="180" class-name="operation-nav" fixed="right">
                <template #default="{ row }">
                    <el-button link type="primary" class="theme-btn" @click="clickDetail(row)">详情</el-button>
                    <el-button link type="primary" class="theme-btn" @click="clickEdit(row)">编辑</el-button>
                    <el-popconfirm title="是否确定删除？" confirm-button-text="确定" cancel-button-text="取消" @confirm="clickDel(row)">
                        <template #reference>
                            <el-button link type="primary" class="theme-btn">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination
            background
            v-model:current-page="page"
            v-model:page-size="pageSize"
            :page-sizes="pageSizeNum"
            :total="totalNums"
            layout="total, sizes, prev, pager, next, jumper"
        >
        </el-pagination>
    </div>
</template>

<script setup>
import { getCurrentInstance, ref, onMounted, watch, onActivated } from "vue"
import { useRouter, onBeforeRouteLeave } from "vue-router"
import { useBaseStore } from "@store/base"
import OneLoad from "@mixins/one-load"
import { Search } from "@element-plus/icons-vue"

const store = useBaseStore()
const router = useRouter()
const { proxy } = getCurrentInstance()

onMounted(() => {
    pubClass()
})

onActivated(() => {
    arr_data.value = []
    getList()
})

// 离开-可以利用这个触发删除页面缓存操作
onBeforeRouteLeave((to, from, next) => {
    if (to.name === "GoodsPublicDetail" || to.name === "GoodsPublicUpdate") {
        store.setInclude("GoodsPublic")
    } else {
        store.delInclude("GoodsPublic")
    }
    next()
})

/**
 * minxin列表加载
 */
const { page, pageSizeNum, pageSize, loading, arr_data, totalNums, search_btn, pubParams, pubRefreshParams, getdata } = OneLoad()

// 切换每页显示条数
watch(pageSize, (val) => {
    page.value = 1
    pubParams(getList)
})
// 跳转第几页
watch(page, (val) => {
    pubParams(getList)
})

function getList() {
    let params = {
        page: page.value,
        limit: pageSize.value,
        so: good_name.value,
        cate_id: class_id.value,
        color_id: colors_id.value,
        level_id: level_id.value,
        s_time: area_time.value ? area_time.value[0] : "",
        l_time: area_time.value ? area_time.value[1] : "",
    }
    getdata("product/common/index", params)
}

// 搜索
const good_name = ref("")
const level_id = ref("")
const colors_id = ref("")
const class_id = ref("")
const area_time = ref("")
const handleSearch = () => {
    search_btn.value = true
    pubRefreshParams(getList)
}

// 公共商品导出
const clickImportOrder = () => {
    proxy.$axios
        .get("product/common/export", {
            params: {
                so: good_name.value,
                cate_id: class_id.value,
                color_id: colors_id.value,
                level_id: level_id.value,
                s_time: area_time.value ? area_time.value[0] : "",
                l_time: area_time.value ? area_time.value[1] : "",
            },
            responseType: "blob",
        })
        .then((res) => {
            let contentDisposition = res.headers["content-disposition"]
            let filename = decodeURI(contentDisposition.split("fileName=")[1] || contentDisposition.split("filename=")[1])
            let blob = new Blob([res.data], { type: res.headers["content-type"] })
            const url = window.URL.createObjectURL(blob)
            const link = document.createElement("a")
            link.href = url
            link.download = filename
            document.body.appendChild(link)
            link.click()
            URL.revokeObjectURL(url) // 释放内存
            document.body.removeChild(link)
        })
        .catch((err) => {})
}

/**
 * 获取商品分类、颜色、等级、物流
 * @param {Array} cate_arrs 分类数组
 */
const pub_options = ref({})
const cate_arrs = ref([])
function pubClass() {
    proxy.$axios
        .get("product/com")
        .then((res) => {
            getList()
            if (res.data.code == 0) {
                let result = res.data.data
                let arrs = []
                let lengths = result.cate_list.length < 24 ? result.cate_list.length : 24
                for (let i = 0; i < lengths; i++) {
                    arrs.push(result.cate_list[i])
                }
                cate_arrs.value = arrs
                pub_options.value = result
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}
// 过滤筛选商品分类
const filterClass = (val) => {
    let classs = []
    pub_options.value.cate_list.forEach((item) => {
        if (item.title.indexOf(val) > -1) {
            classs.push(item)
        }
    })
    cate_arrs.value = classs
}
// 清除分类值事件
const clearCate = () => {
    filterClass("")
}

// 排序
const inputSort = (row) => {
    if (!row.order_by) {
        proxy.$message({ message: "请输入排序数字", type: "warning" })
        return
    }
    proxy.$axios
        .post("product/common/sort", {
            product_common_id: row.product_common_id,
            order_by: row.order_by,
        })
        .then((res) => {
            if (res.data.code == 0) {
                pubParams(getList)
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}

// 添加
const clickAdd = () => {
    router.push({
        path: "/Goods/GoodsPublicUpdate",
        query: {
            type: 1,
        },
    })
}
// 编辑
const clickEdit = (row) => {
    router.push({
        path: "/Goods/GoodsPublicUpdate",
        query: {
            type: 2,
            gid: row.product_common_id,
        },
    })
}

// 删除单个
const clickDel = (row) => {
    postDel(row.product_common_id)
}

// 删除接口
function postDel(params) {
    proxy.$axios
        .post("product/common/delete", {
            product_common_id: params,
        })
        .then((res) => {
            if (res.data.code == 0) {
                pubParams(getList)
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}

const clickDetail = (row) => {
    router.push({
        path: "/Goods/GoodsPublicDetail",
        query: {
            gid: row.product_common_id,
        },
    })
}
</script>
<script>
export default {
    name: "GoodsPublic",
}
</script>

<style lang="less" scoped>
.table-lr__img {
    width: 40px;
    height: 40px;
}
.table-lr__right {
    min-height: 40px;
}
</style>
